
package com.lmx.persistence.service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.lmx.common.util.CommonUtil;
import com.lmx.repoDomain.tmodel.Workorder;
import com.lmx.repoDomain.tmodel.WorkorderAdd;
import com.lmx.repoDomain.tmodel.Customer;
import com.lmx.repoDomain.tmodel.Task;
//import com.lmx.repoDomain.model.*;
import com.lmx.repoDomain.tmodel.business.User;//huibati
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;


/**
 * #{description}
 * 后台工单管理
 * @author shen
 * @version 1.00
 */
@Service
@Scope("prototype")
public class WorkOrderService<T>{
	
	private Log logger = LogFactory.getLog(this.getClass());

    @PersistenceContext
    private EntityManager em;
    
    /**
     * 获取工单列表
     * @param values
     * @return
     */
    public List<Map<String ,Object>> getWorkOrderList(Map<String ,Object> values){
    	
		logger.debug("获取工单列表");
		
		List<Map<String ,Object>> workOrderList = new ArrayList<Map<String ,Object>>();
		
		String query = "select w from Workorder w where w.delStatus != 1";
		
		//企业用户名
		String companyLoginName = (String)values.get("companyLoginName");
		if(companyLoginName != null && !companyLoginName.isEmpty()){
			query = query + " and w.task.pubuser.loginName like '%"+companyLoginName+"%'";
		}
		//任务名
		String taskName = (String)values.get("taskName");
		if(taskName != null && !taskName.isEmpty()){
			query = query + " and w.task.title like '%"+taskName+"%'";
		}
		//客服用户名
		String createloginName = (String)values.get("createloginName");
		if(createloginName != null && !createloginName.isEmpty()){
			query = query + " and w.creater.loginName like '%"+createloginName+"%'";
		}
		//状态
		String isSuccess = (String)values.get("isSuccess");
		if(isSuccess != null && !isSuccess.isEmpty()){
			query = query + " and w.isSuccess = '"+isSuccess+"'";
		}
		//创建时间
		String startTime = (String)values.get("startTime"); 
		String enTime = (String)values.get("enTime");
		if(startTime != null && !startTime.toString().isEmpty() && enTime != null && !enTime.toString().isEmpty()){
			try {
				Integer startInt = CommonUtil.strToIntegerTime(startTime);
				Integer endInt = CommonUtil.strToIntegerTime(enTime);
				query = query + " and w.createTime between "+startInt+" and "+endInt;
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		query = query +" order by w.updateTime desc";
		
		Query qu = this.em.createQuery(query);
		qu.setMaxResults((int)values.get("size"));
		qu.setFirstResult((int)values.get("pageNum"));
		List resultList = qu.getResultList();
				
		for(int i = 0 ; i < resultList.size() ; i ++){
			Workorder workorder = (Workorder) resultList.get(i);
			Map<String ,Object> workorderMap = new HashMap<String, Object>();
			
			Long workOrderID = workorder.getId();
			workorderMap.put("workOrderID", workOrderID.toString());//工单id
			String companyLoginNameStr = "";
			String companyName = "";
			String taskNameStr = "";
			Task task = workorder.getTask();
			if(task != null){
				taskNameStr = task.getTitle();
				User company = task.getPubuser();
				if(company != null){
					companyLoginNameStr = company.getLoginName();
					companyName = company.getEntName();
				}
			}
			workorderMap.put("companyLoginName", companyLoginNameStr==null?companyLoginNameStr="":companyLoginNameStr);//企业用户名
			workorderMap.put("companyName", companyName==null?companyName="":companyName);//企业名称
			workorderMap.put("taskName", taskNameStr==null?taskNameStr="":taskNameStr);//任务名称
			String createloginNameStr = "";
			String createName = "";
			User creater = workorder.getCreater();
			if(creater != null){
				createloginNameStr = creater.getLoginName();
				createName = creater.getName();
			}
			workorderMap.put("createloginName", createloginNameStr==null?createloginNameStr="":createloginNameStr);//客服用户名
			workorderMap.put("createName", createName==null?createName="":createName);//客服姓名
			String title = workorder.getTitle();
			workorderMap.put("title", title==null?title="":title);//工单标题
			String desc = workorder.getDesc();
			workorderMap.put("desc", desc==null?desc="":desc);//工单描述
			Short isSuccessSh = workorder.getIsSuccess();
			workorderMap.put("isSuccess", isSuccessSh==null?isSuccessSh=4:isSuccessSh);//成单状态
			String freezeReason = workorder.getFreezeReason();
			workorderMap.put("freezeReason", freezeReason==null?freezeReason="":freezeReason);//冻结原因
			String customerName = "";
			String customerPhone = "";
			Customer customer = workorder.getCustomer();
			if(customer != null){
				customerName = customer.getName();
				customerPhone = customer.getPhone();
			}
			workorderMap.put("customerName", customerName==null?customerName="":customerName);//客户名称
			workorderMap.put("customerPhone", customerPhone==null?customerPhone="":customerPhone);//客户手机号
			String followTime = "";
			Integer followTimeInt =  workorder.getFollowTime();
			if(followTimeInt != null){
				followTime = CommonUtil.integetTimeForString(followTimeInt);
			}
			workorderMap.put("followTime", followTime);//跟进时间
			String completeTime = "";
			Integer completeTimeInt =  workorder.getCompleteTime();
			if(completeTimeInt != null){
				completeTime = CommonUtil.integetTimeForString(completeTimeInt);
			}
			workorderMap.put("completeTime", completeTime);//成单时间
			String createTime = "";
			Integer createTimeInt =  workorder.getCreateTime();
			if(createTimeInt != null){
				createTime = CommonUtil.integetTimeForString(createTimeInt);
			}
			workorderMap.put("createTime", createTime);//创建时间
			String updateTime = "";
			Integer updateTimeInt =  workorder.getUpdateTime();
			if(updateTimeInt != null){
				updateTime = CommonUtil.integetTimeForString(updateTimeInt);
			}
			workorderMap.put("updateTime",updateTime);//修改时间
			
			workOrderList.add(workorderMap);
		}
		
        return workOrderList;
    }
    
    /**
     * 获取工单列表总条数
     * @param values
     * @return
     */
    public int getWorkOrderListCount(Map<String ,Object> values){
    	
		logger.debug("获取工单列表总条数");
		
		String query = "select count(w.id) from Workorder w where w.delStatus != 1";
		
		//企业用户名
		String companyLoginName = (String)values.get("companyLoginName");
		if(companyLoginName != null && !companyLoginName.isEmpty()){
			query = query + " and w.task.pubuser.loginName like '%"+companyLoginName+"%'";
		}
		//任务名
		String taskName = (String)values.get("taskName");
		if(taskName != null && !taskName.isEmpty()){
			query = query + " and w.task.title like '%"+taskName+"%'";
		}
		//客服用户名
		String createloginName = (String)values.get("createloginName");
		if(createloginName != null && !createloginName.isEmpty()){
			query = query + " and w.creater.loginName like '%"+createloginName+"%'";
		}		
		//状态
		String isSuccess = (String)values.get("isSuccess");
		if(isSuccess != null && !isSuccess.isEmpty()){
			query = query + " and w.isSuccess = '"+isSuccess+"'";
		}		
		//创建时间
		String startTime = (String)values.get("startTime"); 
		String enTime = (String)values.get("enTime");
		if(startTime != null && !startTime.toString().isEmpty() && enTime != null && !enTime.toString().isEmpty()){
			try {
				Integer startInt = CommonUtil.strToIntegerTime(startTime);
				Integer endInt = CommonUtil.strToIntegerTime(enTime);
				query = query + " and w.createTime between "+startInt+" and "+endInt;
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		int count = (int)(long)this.em.createQuery(query)
    			.getSingleResult();
		
        return count;
    }
    
    /**
     * 获取工单详情
     * @param values
     * @return
     */
    public Map<String ,Object> getWorkOrder(Long workOrderID){
    	
			logger.debug("获取工单详情");
		
			Workorder workorder = this.em.find(Workorder.class, workOrderID);
			Map<String ,Object> workorderMap = new HashMap<String, Object>();
			
			workorderMap.put("workOrderID", workOrderID.toString());//工单id
			String companyLoginNameStr = "";
			String companyName = "";
			String taskNameStr = "";
			String taskdesc = "";
			Task task = workorder.getTask();
			if(task != null){
				taskNameStr = task.getTitle();
				taskdesc = task.getDesc();
				User company = task.getPubuser();
				if(company != null){
					companyLoginNameStr = company.getLoginName();
					companyName = company.getEntName();
				}
			}
			workorderMap.put("companyLoginName", companyLoginNameStr==null?companyLoginNameStr="":companyLoginNameStr);//企业用户名
			workorderMap.put("companyName", companyName==null?companyName="":companyName);//企业名称
			workorderMap.put("taskName", taskNameStr==null?taskNameStr="":taskNameStr);//任务名称
			workorderMap.put("taskdesc", taskdesc==null?taskdesc="":taskdesc);//任务描述
			String createloginNameStr = "";
			String createName = "";
			User creater = workorder.getCreater();
			if(creater != null){
				createloginNameStr = creater.getLoginName();
				createName = creater.getName();
			}
			workorderMap.put("createloginName", createloginNameStr==null?createloginNameStr="":createloginNameStr);//客服用户名
			workorderMap.put("createName", createName==null?createName="":createName);//客服姓名
			String title = workorder.getTitle();
			workorderMap.put("title", title==null?title="":title);//工单标题
			String desc = workorder.getDesc();
			workorderMap.put("desc", desc==null?desc="":desc);//工单描述
			Short isSuccessSh = workorder.getIsSuccess();
			workorderMap.put("isSuccess", isSuccessSh==null?isSuccessSh=4:isSuccessSh);//成单状态
			String freezeReason = workorder.getFreezeReason();
			workorderMap.put("freezeReason", freezeReason==null?freezeReason="":freezeReason);//冻结原因
			String customerName = "";
			String customerPhone = "";
			Customer customer = workorder.getCustomer();
			if(customer != null){
				customerName = customer.getName();
				customerPhone = customer.getPhone();
			}
			workorderMap.put("customerName", customerName==null?customerName="":customerName);//客户名称
			workorderMap.put("customerPhone", customerPhone==null?customerPhone="":customerPhone);//客户手机号
			String followTime = "";
			Integer followTimeInt =  workorder.getFollowTime();
			if(followTimeInt != null){
				followTime = CommonUtil.integetTimeForString(followTimeInt);
			}
			workorderMap.put("followTime", followTime);//跟进时间
			String completeTime = "";
			Integer completeTimeInt =  workorder.getCompleteTime();
			if(completeTimeInt != null){
				completeTime = CommonUtil.integetTimeForString(completeTimeInt);
			}
			workorderMap.put("completeTime", completeTime);//成单时间
			String createTime = "";
			Integer createTimeInt =  workorder.getCreateTime();
			if(createTimeInt != null){
				createTime = CommonUtil.integetTimeForString(createTimeInt);
			}
			workorderMap.put("createTime", createTime);//创建时间
			String updateTime = "";
			Integer updateTimeInt =  workorder.getUpdateTime();
			if(updateTimeInt != null){
				updateTime = CommonUtil.integetTimeForString(updateTimeInt);
			}
			workorderMap.put("updateTime",updateTime);//修改时间
			String remark = workorder.getRemark();
			workorderMap.put("remark", remark==null?remark="":remark);//备注
			
			//工单追加信息列表
			List<Map<String ,Object>> workOrderAddList = new ArrayList<Map<String ,Object>>();
			
			String query = "select wa from WorkorderAdd wa where wa.delStatus != 1 and wa.workorder.id = ?1 order by wa.createTime desc";
			
			Query qu = this.em.createQuery(query);
			qu.setParameter(1, workOrderID);
			List resultList = qu.getResultList();
					
			for(int i = 0 ; i < resultList.size() ; i ++){
				WorkorderAdd workorderAdd = (WorkorderAdd) resultList.get(i);
				Map<String ,Object> WorkorderAddMap = new HashMap<String, Object>();
				
				Long workorderAddID = workorderAdd.getId();
				WorkorderAddMap.put("workorderAddID", workorderAddID.toString());//工单追加信息id
				String content = workorderAdd.getContent();
				WorkorderAddMap.put("content", content==null?content="":content);//内容
				String additionalLoginName = "";
				String additionalName = "";
				User additional = workorderAdd.getAdditional();
				if(additional != null){
					additionalLoginName = additional.getLoginName();
					additionalName = additional.getName();
				}
				WorkorderAddMap.put("additionalLoginName", additionalLoginName==null?additionalLoginName="":additionalLoginName);//追加人
				WorkorderAddMap.put("additionalName", additionalName==null?additionalName="":additionalName);//追加人姓名
				String remindTime = "";
				Integer remindTimeInt =  workorderAdd.getRemindTime();
				if(remindTimeInt != null){
					remindTime = CommonUtil.integetTimeForString(remindTimeInt);
				}
				WorkorderAddMap.put("remindTime", remindTime);//提醒时间
				String createTimeAdd = "";
				Integer createTimeAddInt =  workorderAdd.getCreateTime();
				if(createTimeAddInt != null){
					createTimeAdd = CommonUtil.integetTimeForString(createTimeAddInt);
				}
				WorkorderAddMap.put("createTimeAdd", createTimeAdd);//创建时间
				String remarkAdd = workorderAdd.getRemark();
				WorkorderAddMap.put("remarkAdd", remarkAdd==null?remarkAdd="":remarkAdd);//备注
				
				workOrderAddList.add(WorkorderAddMap);
			}
			workorderMap.put("workOrderAddList", workOrderAddList);
			
        return workorderMap;
    }
    
    /**
     * 修改成单状态
     * @param user
     * @return
     */
    @Transactional
    public void updateWorkorderIsSuccess(Workorder workorder){
    	
		logger.debug("修改修改成单状态");
		
		String query = "update Workorder w set w.isSuccess = ?1 , w.updateTime = ?3 where w.id = ?2";
		
		//修改成单状态
        this.em.createQuery(query)
                .setParameter(1, workorder.getIsSuccess())
                .setParameter(2, workorder.getId())
                .setParameter(3, CommonUtil.getCurrTimes())
                .executeUpdate();
    }
}
